package com.younion.action.manage;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.cache.support.SimpleValueWrapper;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.younion.business.ICustomerService;
import com.younion.business.IMemberCardService;
import com.younion.business.IMsgTemplateService;
import com.younion.business.IRegisterUserService;
import com.younion.business.IRolesService;
import com.younion.business.ISendMsgService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.MsgStatus;
import com.younion.common.constants.MsgType;
import com.younion.common.constants.RoleType;
import com.younion.common.constants.Schedule;
import com.younion.common.constants.Status;
import com.younion.common.constants.TemplateScope;
import com.younion.common.constants.TemplateTargetType;
import com.younion.common.exception.BaseException;
import com.younion.common.paginator.Paginator;
import com.younion.common.system.SystemConfig;
import com.younion.util.YounionUtil;
import com.younion.vo.CustomerVO;
import com.younion.vo.MemberCardVO;
import com.younion.vo.MsgTemplateVO;
import com.younion.vo.RegisterUserVO;
import com.younion.vo.RolesVO;
import com.younion.vo.SendMsgVO;

import cpcns.jhsks.util.MapCollectionUtils;

/**
 * @author Joe Chen
*/
public class SendMsgAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	protected static final Log logger = LogFactory.getLog(SendMsgAction.class);

	private ISendMsgService sendMsgService = null;

	private SendMsgVO sendMsgVO = new SendMsgVO();

	private List<SendMsgVO> sendMsgList;//  结果集列表
	
	private List<Schedule> schedules = Arrays.asList(Schedule.values());
	
	private List<MsgType> msgTypes = Arrays.asList(MsgType.values());
	
	private List<MsgStatus> statuses = Arrays.asList(MsgStatus.values());
	
	private List<MsgTemplateVO> templates = null;
	
	private Collection membercards = null;
	
	@Autowired
	private IRolesService rolesService = null;
	
	@Autowired
	private IMsgTemplateService msgTemplateService = null;
	@Autowired
	private IMemberCardService memberCardService = null;
	//@Autowired	
	//private ICustomerAccountService customerAccountService = null;
	@Autowired	
	private ICustomerService customerService = null;
	
	@Autowired
	private IRegisterUserService registerUserService = null;
	
	@Autowired
	private SimpleCacheManager simpleCacheManager = null;
	
	private String memberIds = null;
	/**
	 * 列表：翻页区；数据区
	 */
	@RequiresPermissions("listSendMsg")
	@SuppressWarnings("unchecked")
	public String listSendMsg() {
		try {
			Map paramMap = null;
			if (sendMsgVO != null) {
				if("".equals(sendMsgVO.getUsers()))
					sendMsgVO.setUsers(null);
				if(getSessionUser().getCustomer() != null){
					sendMsgVO.setCustomer(getSessionUser().getCustomer());
				}
				if(sendMsgVO.getTemplate() != null && sendMsgVO.getTemplate().getId() < 0)
					sendMsgVO.setTemplate(null);
				paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(sendMsgVO));
			}
			// 获取总记录数
			int total = sendMsgService.getCountByMap(paramMap);
			// 根据总记录数获取分页对象
			Paginator paginator = this.getPaginator(total);
			sendMsgList = sendMsgService.get(paramMap, paginator);
			//保存分页对象
			this.savaPaginator(paginator);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}

	/**
	 * 新增
	 */
	@RequiresPermissions("addSendMsg")
	public String addSendMsg() {
		String pkId = request.getParameter("ids");
		sendMsgVO.setUsers(pkId);
		setupTemplates();
		return SUCCESS;
	}

	/**
	 * 修改保存，调度Jsp
	 */
	@RequiresPermissions("editSendMsg")
	public String editSendMsg() {
		try {
			sendMsgVO = sendMsgService.getById(sendMsgVO.getId().toString());
			setupTemplates();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 保存动作
	 */
	@RequiresPermissions("saveSendMsg")
	public String saveSendMsg() {
		try {
			if(sendMsgVO.getId() != null){
				sendMsgService.save(sendMsgVO);
				this.addLog(3, "修改发送短信：["+this.sendMsgVO.getId()+"]", "修改发送短信",getSessionUser());
				return SUCCESS;
			}
			List<MemberCardVO> memberCards = Lists.newArrayList();
			if(sendMsgVO.getUsers() != null && "ALL".equalsIgnoreCase(sendMsgVO.getUsers())){
				//Load search params from cache
				SimpleValueWrapper simplevaluewrapper = (SimpleValueWrapper) simpleCacheManager.getCache(CACHE_KEY).get(getSessionUser().getId());
				Map paramMap = (Map) simplevaluewrapper.get();
				if(getSessionUser().getCustomer() != null)
					paramMap.put("customerId", getSessionUser().getCustomer().getId());
				Collection membercards = memberCardService.getByMap(paramMap);
				memberCards.addAll(membercards);
			}else{
				memberCards = memberCardService.selectByIds(Arrays.asList(sendMsgVO.getUsers().split(",")));
			}
			if(memberCards.size() == 0){
				tipMessage = "没有会员卡可发送！";
				request.setAttribute("tipMessage", tipMessage);
				return ERROR;
			}
			RolesVO role = rolesService.getById(getSessionUser().getRole().toString());
			if(getSessionUser().getCustomer() == null && !RoleType.SUPPER.getName().equals(role.getRoleType())){
				tipMessage = "你没有权限管理该商家";
				request.setAttribute("tipMessage", tipMessage);
				return ERROR;
			}
			CustomerVO customer = null; 
			//CustomerAccountVO customerAccount = null;
			Map paramMap = Maps.newHashMap();
			if(!RoleType.SUPPER.getName().equals(role.getRoleType())){
				customer = customerService.getById(getSessionUser().getCustomer().getId().toString());
				//customerAccount = customerAccountService.getById(customer.getCustomerAccountId().toString());
			}
			
			List<SendMsgVO> msgs = generateMsgContent(memberCards);
			String unitStr = SystemConfig.getInstance().getPropValue("sendmsg.cut.money");
			Integer unit = Integer.valueOf(unitStr);
			double money = msgs.size() * unit;			
			if(customer != null ){
				if(customer.getMoney() == null || money > customer.getMoney()){
					tipMessage = "你的余额不足，请充值";
					request.setAttribute("tipMessage", tipMessage);
					return ERROR;
				}else{
					//paramMap.put("money", customerAccount.getMoney() - money);
					//paramMap.put("id", customerAccount.getId());
					paramMap.put("money", customer.getMoney() - money);
					paramMap.put("id", customer.getId());
				}
			}
			
			sendMsgService.insertSendMsg(msgs,paramMap);
			String templateId = (sendMsgVO.getTemplate() == null || sendMsgVO.getTemplate().getId() == null)? "" : sendMsgVO.getTemplate().getId().toString();
			this.addLog(3, "发送短信：会员卡["+sendMsgVO.getUsers()+"],模板：" + templateId, "发送短信",getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			return ERROR;
		}
		request.setAttribute("refreshNavTabId", "sendMsgList");
		request.setAttribute("callbackType", "forward");
		request.setAttribute("dialogId", "sendMsgDialog");
		request.setAttribute("forwardUrl", request.getContextPath()+"/memberCard/listMemberCard.action");
		return SUCCESS;
	}

	private List<SendMsgVO> generateMsgContent(List<MemberCardVO> memberCards) throws BaseException {
		List<SendMsgVO> msgs = Lists.newArrayList();
		for(MemberCardVO card : memberCards){
			SendMsgVO msg = new SendMsgVO();
			RegisterUserVO user = registerUserService.getByMemberCard(card);
			if(user != null){
				msg.setSendTime(sendMsgVO.getSendTime()==null?new Date():sendMsgVO.getSendTime());
				msg.setStatus(MsgStatus.UNSEND.getName());
				msg.setTemplate(sendMsgVO.getTemplate());
				msg.setUsers(card.getId().toString());
				msg.setCustomer(this.getSessionUser().getCustomer());
				String content = YounionUtil.generateMessageContent(sendMsgVO.getContent(), card);
				msg.setContent(content);
				msg.setMobile(user.getLoginId());
				msgs.add(msg);
			}
		}
		return msgs;
	}

	/**
	 * 删除
	 */
	@RequiresPermissions("deleteSendMsg")
	public String deleteSendMsg() {
		try {
			String pkId = request.getParameter("ids");
			sendMsgService.remove(Arrays.asList(pkId.split(",")));
			this.addLog(3, "删除发送信息：["+pkId+"]", "删除发送信息",getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "sendMsgList");
		return SUCCESS;
	}
	/**
	 * 查看鿴
	 */
	@RequiresPermissions("viewSendMsg")
	public String viewSendMsg() {
		try {
			sendMsgVO = sendMsgService.getById(sendMsgVO.getId().toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;

	}
	
	private void setupTemplates(){
		templates = Lists.newArrayList();
		Map paramMap = Maps.newHashMap();
		try {
			//paramMap.put("status",Status.APPROVABLE.getName());
			paramMap.put("status",Status.ACTIVE.getName());
			paramMap.put("scope", TemplateScope.SMS.getName());
			paramMap.put("targetType", TemplateTargetType.COMMON.getName());
			if(getSessionUser().getCustomer() != null){
				paramMap.put("customerId", getSessionUser().getCustomer().getId());
			}
			Collection msgs = msgTemplateService.getByMap(paramMap);
			paramMap.put("scope", TemplateScope.ALL.getName());
			msgs.addAll(msgTemplateService.getByMap(paramMap));
			Iterator it  = msgs.iterator();
			while(it.hasNext()){
				templates.add((MsgTemplateVO)it.next());
			}
		} catch (BaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 发送短信
	 * @return
	 */
	@RequiresPermissions("sendMsg")
	public String sendMsg(){
		try {
			String pkId = request.getParameter("ids");
			if(pkId == null){
				tipMessage = "请选择会员卡";
				request.setAttribute("tipMessage", tipMessage);
				return ERROR;
			}else if("ALL".equalsIgnoreCase(pkId)){
				memberIds = "ALL";
			}else{
				memberIds = pkId.substring(0,pkId.length()-1);
			}
			setupTemplates();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public SendMsgVO getSendMsgVO() {
		return sendMsgVO;
	}

	public void setSendMsgVO(SendMsgVO sendMsgVO) {
		this.sendMsgVO = sendMsgVO;
	}

	public void setSendMsgService(ISendMsgService sendMsgService) {
		this.sendMsgService = sendMsgService;
	}

	public List<SendMsgVO> getSendMsgList() {
		return sendMsgList;
	}

	public void setSendMsgList(List<SendMsgVO> sendMsgList) {
		this.sendMsgList = sendMsgList;
	}

	public List<Schedule> getSchedules() {
		return schedules;
	}

	public void setSchedules(List<Schedule> schedules) {
		this.schedules = schedules;
	}

	public ISendMsgService getSendMsgService() {
		return sendMsgService;
	}

	public List<MsgType> getMsgTypes() {
		return msgTypes;
	}

	public void setMsgTypes(List<MsgType> msgTypes) {
		this.msgTypes = msgTypes;
	}

	public List<MsgTemplateVO> getTemplates() {
		if(templates == null){
			setupTemplates();
		}
		return templates;
	}

	public void setTemplates(List<MsgTemplateVO> templates) {
		this.templates = templates;
	}

	public IMsgTemplateService getMsgTemplateService() {
		return msgTemplateService;
	}

	public void setMsgTemplateService(IMsgTemplateService msgTemplateService) {
		this.msgTemplateService = msgTemplateService;
	}

	public String getMemberIds() {
		return memberIds;
	}

	public void setMemberIds(String memberIds) {
		this.memberIds = memberIds;
	}

	public IMemberCardService getMemberCardService() {
		return memberCardService;
	}

	public void setMemberCardService(IMemberCardService memberCardService) {
		this.memberCardService = memberCardService;
	}

	/*public ICustomerAccountService getCustomerAccountService() {
		return customerAccountService;
	}

	public void setCustomerAccountService(
			ICustomerAccountService customerAccountService) {
		this.customerAccountService = customerAccountService;
	}*/

	public ICustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public List<MsgStatus> getStatuses() {
		return statuses;
	}

	public void setStatuses(List<MsgStatus> statuses) {
		this.statuses = statuses;
	}

	public IRolesService getRolesService() {
		return rolesService;
	}

	public void setRolesService(IRolesService rolesService) {
		this.rolesService = rolesService;
	}

	public void setMembercards(List<MemberCardVO> membercards) {
		this.membercards = membercards;
	}

	public Collection getMembercards() {
		if(membercards == null){
			try {
				if(this.getSessionUser().getCustomer() == null){
					membercards = memberCardService.getAll();
				}else{
					Map paramMap = Maps.newHashMap();
					paramMap.put("customerId",this.getSessionUser().getCustomer().getId());
					membercards = memberCardService.getByMap(paramMap);
				}
			} catch (Exception e) {
			}
		}
		return membercards;
	}

	public void setMembercards(Collection membercards) {
		this.membercards = membercards;
	}

	public IRegisterUserService getRegisterUserService() {
		return registerUserService;
	}

	public void setRegisterUserService(IRegisterUserService registerUserService) {
		this.registerUserService = registerUserService;
	}

	public SimpleCacheManager getSimpleCacheManager() {
		return simpleCacheManager;
	}

	public void setSimpleCacheManager(SimpleCacheManager simpleCacheManager) {
		this.simpleCacheManager = simpleCacheManager;
	}
	
	
}